package com.tianji.remark.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.StringUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.constans.RedisConstants;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.remark.domain.dto.LikedTimesDTO;
import com.tianji.remark.domain.po.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.ILikedRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-01-26
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class LikedRecordRedisServiceImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {

    private final RabbitMqHelper rabbitMqHelper;
    private final StringRedisTemplate redisTemplate;
    /**
     *
     * @param dto
     */
    @Override
    public void addLikeRecord(LikeRecordFormDTO dto) {
        //1.获取当前登录用户
        Long userId = UserContext.getUser();

        //2.判断是否点赞 dto.liked 为true是点赞
        boolean flag = dto.getLiked() ? liked(dto,userId) : unliked(dto,userId);
        if (!flag){//说明点或赞或取消赞
            return;
        }
        //3.统计该业务id下的总点赞数
        /*Integer totalLikesNum = this.lambdaQuery()
                .eq(LikedRecord::getBizId, dto.getBizId())
                .count();*/
        //基于redis
        // 获取Key
        String key = RedisConstants.LIKE_BIZ_KEY_PREFIX + dto.getBizId();
        Long totalLikesNum = redisTemplate.opsForSet().size(key);
        if (totalLikesNum == null){
            return;
        }

        //4.采用zset结构缓存点赞数量
        String bizTypeTotalLikeKey = RedisConstants.LIKE_BIZ_KEY_PREFIX + dto.getBizType();
        redisTemplate.opsForZSet().add(bizTypeTotalLikeKey,dto.getBizId().toString(),totalLikesNum);
//        redisTemplate.opsForZSet().add(
//                RedisConstants.LIKE_COUNT_KEY_PREFIX + dto.getBizType(),
//                dto.getBizId().toString(),
//                totalLikesNum
//        );

/*        //4.发生消息到mq
        *//*String routingKey = StringUtils.format(MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE, dto.getBizType());
        LikedTimesDTO msg = LikedTimesDTO.of(dto.getBizId(), totalLikesNum);

        log.debug("发送点赞消息,消息内容{}",msg);
        rabbitMqHelper.send(
                MqConstants.Exchange.LIKE_RECORD_EXCHANGE,
                routingKey,
                msg);*/
    }

    //取消赞
    private boolean unliked(LikeRecordFormDTO dto,Long userId) {
        // 获取Key
        String key = RedisConstants.LIKE_BIZ_KEY_PREFIX + dto.getBizId();
        // 执行SADD命令
        Long result = redisTemplate.boundSetOps(key).add(userId.toString());
        return result != null && result > 0;

/*        LikedRecord record = this.lambdaQuery()
                .eq(LikedRecord::getUserId, userId)
                .eq(LikedRecord::getBizId, dto.getBizId())
                .one();
        if (record == null){
            //说明之前没点过赞
            return false;
        }
        //删除点赞记录
        boolean result = this.removeById(record.getId());
        return result;*/
    }

    //点赞
    private boolean liked(LikeRecordFormDTO dto,Long userId) {
        // 获取Key
        String key = RedisConstants.LIKE_BIZ_KEY_PREFIX + dto.getBizId();
        // 执行SREM命令
        Long result = redisTemplate.opsForSet().remove(key, userId.toString());
        return result != null && result > 0;

/*        LikedRecord record = this.lambdaQuery()
                .eq(LikedRecord::getUserId, userId)
                .eq(LikedRecord::getBizId, dto.getBizId())
                .one();
        if (record != null){
            //说明之前点过赞
            return false;
        }
        //保存点赞记录到表
        LikedRecord likedRecord = new LikedRecord();
        likedRecord.setUserId(userId);
        likedRecord.setBizId(dto.getBizId());
        likedRecord.setBizType(dto.getBizType());
        boolean result = this.save(likedRecord);
        return result;*/
    }

    /**
     * 批量查询点赞状态
     * @param bizIds
     * @return
     */
    @Override
    public Set<Long> getLikesStatusByBizIds(List<Long> bizIds) {
      /*  //1.获取用户
        Long userId = UserContext.getUser();
        if (CollUtils.isEmpty(bizIds)){
            return CollUtils.emptySet();
        }
        //2.循环bizIds
        Set<Long> likedBizIds = new HashSet<>();
        for (Long bizId : bizIds) {
            //判断当前业务id 的点赞用户集合中是否包含当前用户
            Boolean member = redisTemplate.opsForSet().isMember(RedisConstants.LIKE_BIZ_KEY_PREFIX + bizId, userId.toString());
            if (member){
                likedBizIds.add(bizId);
            }
        }
        return likedBizIds;*/

        // 1.获取登录用户id
        Long userId = UserContext.getUser();
        // 2.查询点赞状态  短时间 大量处理redis命令
        List<Object> objects = redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
            StringRedisConnection src = (StringRedisConnection) connection;
            for (Long bizId : bizIds) {
                String key = RedisConstants.LIKE_BIZ_KEY_PREFIX + bizId;
                src.sIsMember(key, userId.toString());
            }
            return null;
        });
        // 3.返回结果
        return IntStream.range(0, objects.size()) // 创建从0到集合size的流
                .filter(i -> (boolean) objects.get(i)) // 遍历每个元素，保留结果为true的角标i
                .mapToObj(bizIds::get)// 用角标i取bizIds中的对应数据，就是点赞过的id
                .collect(Collectors.toSet());// 收集
    }

    @Override
    public void readLikedTimesAndSendMessage(String bizType, int maxBizSize) {
        //拼接key
        String bizTypeTotalLikeKey = RedisConstants.LIKE_BIZ_KEY_PREFIX + bizType;

        List<LikedTimesDTO> list = new ArrayList<>();
        //2.从redis的zset结构中 按分数排序取 maxBizSize的业务点赞信息
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisTemplate.opsForZSet().popMin(bizTypeTotalLikeKey, maxBizSize);
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            String bizId = typedTuple.getValue();
            Double likedTimes = typedTuple.getScore();
            if (StringUtils.isBlank(bizId) || likedTimes==null){
                continue;
            }
            //3.封装LikedTimeDTO
            LikedTimesDTO msg = LikedTimesDTO.of(Long.valueOf(bizId), likedTimes.intValue());
            list.add(msg);
        }

        //4.发送消息到mq
        if (CollUtils.isNotEmpty(list)){
            rabbitMqHelper.send(
                    MqConstants.Exchange.LIKE_RECORD_EXCHANGE,
                    StringUtils.format(MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE, bizType),
                    list);
        }
    }
}
